//
//  CLNetworkTools.swift
//  weibo001
//
//  Created by CL on 16/7/10.
//  Copyright © 2016年 CL. All rights reserved.
//

import UIKit
import AFNetworking

//定义请求类型的枚举,
enum RequestType: Int {
    case GET
    case POST
}


class CLNetworkTools: AFHTTPSessionManager {
  //单例全局访问点
    static let sharedTools: CLNetworkTools = {
       let tools =  CLNetworkTools()
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    } ()
    
    //封装get/post 请求
    func request(type: RequestType, url: String , params:AnyObject?, callBack:(response:AnyObject?, error: NSError?) ->()) {
        
        if type == .GET {
            
            GET(url,parameters: params, progress: nil, success: {(_, response) -> Void in
                callBack(response: response, error: nil)
                
                },failure: { (_, error) -> Void in
                    callBack(response: nil, error: error)
            })
            
            
        }else {
            
            POST(url, parameters: params, success: { (_, response) -> Void in
                
                callBack(response: response, error: nil)
                
                }, failure: { (_, error) -> Void in
                     callBack(response: nil, error: error)
            })
            
            
        }
      
    }
    
 
    
}



extension CLNetworkTools {
    //通过授权码(code)获取accesstoken
  func requestAccesstoken(code: String, callBack: (response: AnyObject?, error: NSError?) -> ()) {
    // 准备接口地址
     let url = "https://api.weibo.com/oauth2/access_token"
    
    //准备参数
    
    let params = [
        "client_id": WeiboAppKey,
        "client_secret": WeiboAppSecret,
        "grant_type": "authorization_code",
        "code": code,
        "redirect_uri": WeiboRedirect_Uri
    
    ]
    //使用通用接口去请求
     request(.POST,url: url, params: params, callBack: callBack)
    
    
    }
    //获取用户信息
//    func requestUserInfo(userAccount:CLUserAccount, callBack: (response: AnyObject?, error: NSError?) -> ()) {
//    //请求接口地址
//    let url = "https://api.weibo.com/2/users/show.json"
//    
//        //准备请求参数
//        let params = [
//        
//            "access_token": userAccount.access_token!,
//            "uid": "\(userAccount.uid)"
//        
//        ]
//        request(.GET, url: url, params: params, callBack: callBack)
//    }
//    
}





